package iscript.uiFramework.components.core 
{
	import flash.display.DisplayObject;
	import flash.display.DisplayObjectContainer;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import iscript.uiFramework.components.window.IWindow;
	import iscript.uiFramework.UIFramework;
	import iscript.uiFramework.util.UIComponentUtil;

	public class PopupManager
	{
		
		
		{
			UIFramework.UiStage.addEventListener(Event.RESIZE,resizeUIStageLogic)
		}
		
		static private function resizeUIStageLogic(e:Event):void {
			  if (_keepTopTarget) {
				    if (_keepTopTarget is IWindow) {
							_keepTopTarget.x =  UIFramework.UiStage.stageWidth*0.5 -  _keepTopTarget.width*0.5 
							_keepTopTarget.y =  UIFramework.UiStage.stageHeight*0.5 -  _keepTopTarget.height*0.5 
						}
				  }
			}
		
		public function PopupManager() 
		{
				
		}
		
		//static  private var _windowList:Vector.<DisplayObject> = new Vector.<DisplayObject>();
		
		static private var _keepTopTarget:DisplayObject;
		
		static public function append(target:DisplayObject,container:DisplayObjectContainer = null):void {
			  UIComponentUtil.addChild(target, container);
				  if (target is IWindow) {
						IWindow(target).open();
					  }
				  target.addEventListener(MouseEvent.MOUSE_DOWN, _toTopLogic);
				  target.addEventListener(Event.REMOVED_FROM_STAGE, _removeTarget);

				  keepTop(_keepTopTarget);
			}			
			
		static private function _removeTarget(e:Event):void 
		{
		 	DisplayObject(e.currentTarget).removeEventListener(Event.REMOVED_FROM_STAGE, _removeTarget);
			DisplayObject(e.currentTarget).removeEventListener(MouseEvent.MOUSE_DOWN, _toTopLogic);
		}
			
		static public function remove(target:DisplayObject):void {
			   if (target.parent)
			   target.parent.removeChild(target);  
			}
			
		static private function	_toTopLogic(e:MouseEvent):void {
			     var target:DisplayObject = DisplayObject(e.currentTarget)				 
				target.stage.setChildIndex(target, target.stage.numChildren - 1);
				keepTop(_keepTopTarget);
			}
			
			
	/*	public function top(target:DisplayObject):void {
			   if(target.parent)
			   target.parent.setChildIndex(target, target.parent.numChildren - 1);
			}
		public function bottom(target:DisplayObject):void {
			   if(target.parent)
			   target.parent.setChildIndex(target, 0);
			}*/		
			
		static public function keepTop(target:DisplayObject):void {
			    _keepTopTarget = target;
				if (_keepTopTarget != null && _keepTopTarget.stage != null) {
					
			    _keepTopTarget.stage.setChildIndex(IWindow(_keepTopTarget).maskComponent, target.stage.numChildren - 1);
			    _keepTopTarget.stage.setChildIndex(target, target.stage.numChildren - 1);
				}
			
			 }
	}

}